﻿#include "RecentList.h"
#include "Notification.h"
#include <QMouseEvent>
#include <QPainter>
#include <QScrollBar>
#include <QPropertyAnimation>
#include <QInputDialog>
#include <QApplication>
#include <QFileInfo>
#include <QMenu>
#include <QClipboard>
#include <QToolTip>
#include <QDesktopServices>
#include <QUrl>
#include <QFileDialog>
#include <QProcess>

// ========== RecentItem实现 ==========

RecentItem::RecentItem(const QString& name, const QDateTime& timestamp, QWidget* parent)
	: QWidget(parent), m_isHovered(false)
{
	setupUI();
	setName(name);
	setTimestamp(timestamp);

	connect(&ThemeManager::GetInstance(), &ThemeManager::themeChanged, this, &RecentItem::onThemeChanged);

	// 立即应用当前主题
	ThemeManager::Theme currentTheme = ThemeManager::GetInstance().currentTheme();
	if (currentTheme == ThemeManager::Theme::Dark) {
		setDarkTheme();
	}
	else {
		setLightTheme();
	}
}

RecentItem::RecentItem(const QString& name, const QString& timestampStr, QWidget* parent)
	: QWidget(parent), m_isHovered(false)
{
	setupUI();
	setName(name);
	setTimestamp(timestampStr);

	connect(&ThemeManager::GetInstance(), &ThemeManager::themeChanged, this, &RecentItem::onThemeChanged);

	// 立即应用当前主题
	ThemeManager::Theme currentTheme = ThemeManager::GetInstance().currentTheme();
	if (currentTheme == ThemeManager::Theme::Dark) {
		setDarkTheme();
	}
	else {
		setLightTheme();
	}
}

RecentItem::~RecentItem()
{
	delete m_contextMenu;
	delete m_renameAction;
	delete m_copyPathAction;
	delete m_cutPathAction;
	delete m_openInExplorerAction;
}

void RecentItem::setDarkTheme()
{
	m_nameLabel->setStyleSheet("color: #D4D4D4; background-color: transparent;");
	m_timestampLabel->setStyleSheet("color: #858585; background-color: transparent;");

	m_deleteBtn->setStyleSheet(R"(
        QPushButton {
            background-color: transparent;
            border: none;
            color: #7A7A7A;
            font-size: 16px;
            font-weight: bold;
            border-radius: 10px;
        }
        QPushButton:hover {
            background-color: #FF5252;
            color: #FFFFFF;
        }
    )");

	m_contextMenu->setStyleSheet(R"(
        QMenu {
            background-color: #2D2D30;
            border: 1px solid #3E3E42;
            border-radius: 6px;
            padding: 4px;
            color: #E8E8E8;
        }
        QMenu::item {
            padding: 6px 16px;
            border-radius: 4px;
            font-size: 13px;
        }
        QMenu::item:selected {
            background-color: #3E3E42;
            color: #FFFFFF;
        }
        QMenu::item:disabled {
            color: #7A7A7A;
        }
        QMenu::separator {
            height: 1px;
            background-color: #3E3E42;
            margin: 4px 8px;
        }
    )");

	update();
}

void RecentItem::setLightTheme()
{
	m_nameLabel->setStyleSheet("color: #2C3E50; background-color: transparent;");
	m_timestampLabel->setStyleSheet("color: #7F8C8D; background-color: transparent;");

	m_deleteBtn->setStyleSheet(R"(
        QPushButton {
            background-color: transparent;
            border: none;
            color: #95A5A6;
            font-size: 16px;
            font-weight: bold;
            border-radius: 10px;
        }
        QPushButton:hover {
            background-color: #FF5252;
            color: #FFFFFF;
        }
    )");

	m_contextMenu->setStyleSheet(R"(
        QMenu {
            background-color: #FFFFFF;
            border: 1px solid #E1E5E9;
            border-radius: 6px;
            padding: 4px;
            color: #495057;
        }
        QMenu::item {
            padding: 6px 16px;
            border-radius: 4px;
            font-size: 13px;
        }
        QMenu::item:selected {
            background-color: #E7F3FF;
            color: #4A90E2;
        }
        QMenu::item:disabled {
            color: #ADB5BD;
        }
        QMenu::separator {
            height: 1px;
            background-color: #E9ECEF;
            margin: 4px 8px;
        }
    )");

	update();
}

void RecentItem::setupUI()
{
	setAttribute(Qt::WA_Hover, true);
	setMouseTracking(true);

	m_mainLayout = new QHBoxLayout(this);
	m_mainLayout->setContentsMargins(12, 8, 12, 8);
	m_mainLayout->setSpacing(8);

	m_deleteBtn = new QPushButton("×", this);
	m_deleteBtn->setFixedSize(20, 20);
	m_deleteBtn->setStyleSheet(R"(
        QPushButton {
            background-color: transparent;
            border: none;
            color: #95A5A6;
            font-size: 16px;
            font-weight: bold;
            border-radius: 10px;
        }
        QPushButton:hover {
            background-color: #FF5252;
            color: #FFFFFF;
        }
    )");
	m_deleteBtn->setCursor(Qt::PointingHandCursor);
	m_deleteBtn->hide();

	connect(m_deleteBtn, &QPushButton::clicked, this, [this]() {
		emit deleteRequested(m_filePath);
		});

	m_nameLabel = new QLabel(this);
	m_nameLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
	QFont nameFont = m_nameLabel->font();
	nameFont.setPointSize(11);
	nameFont.setWeight(QFont::Medium);
	m_nameLabel->setFont(nameFont);
	m_nameLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);

	m_timestampLabel = new QLabel(this);
	m_timestampLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);
	QFont timestampFont = m_timestampLabel->font();
	timestampFont.setPointSize(10);
	m_timestampLabel->setFont(timestampFont);
	m_timestampLabel->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Preferred);

	m_mainLayout->addWidget(m_deleteBtn, 0);
	m_mainLayout->addWidget(m_nameLabel, 1);
	m_mainLayout->addWidget(m_timestampLabel, 0);

	setLayout(m_mainLayout);
	setCursor(Qt::PointingHandCursor);
	setMinimumHeight(42);

	// 初始化右键菜单
	m_contextMenu = new QMenu(this);
	m_contextMenu->setStyleSheet(R"(
        QMenu {
            background-color: #FFFFFF;
            border: 1px solid #E1E5E9;
            border-radius: 6px;
            padding: 4px;
            color: #495057;
        }
        QMenu::item {
            padding: 6px 16px;
            border-radius: 4px;
            font-size: 13px;
        }
        QMenu::item:selected {
            background-color: #E7F3FF;
            color: #4A90E2;
        }
        QMenu::item:disabled {
            color: #ADB5BD;
        }
        QMenu::separator {
            height: 1px;
            background-color: #E9ECEF;
            margin: 4px 8px;
        }
    )");

	m_renameAction = new QAction("重命名", this);
	m_copyPathAction = new QAction("复制文件路径", this);
	m_cutPathAction = new QAction("剪切文件路径", this);
	m_openInExplorerAction = new QAction("在资源管理器中打开", this);

	m_contextMenu->addAction(m_renameAction);
	m_contextMenu->addSeparator();
	m_contextMenu->addAction(m_copyPathAction);
	m_contextMenu->addAction(m_cutPathAction);
	m_contextMenu->addSeparator();
	m_contextMenu->addAction(m_openInExplorerAction);

	connect(m_renameAction, &QAction::triggered, this, &RecentItem::onRenameActionTriggered);
	connect(m_copyPathAction, &QAction::triggered, this, &RecentItem::onCopyPathActionTriggered);
	connect(m_cutPathAction, &QAction::triggered, this, &RecentItem::onCutPathActionTriggered);
	connect(m_openInExplorerAction, &QAction::triggered, this, &RecentItem::onOpenInExplorerActionTriggered);
}

void RecentItem::onRenameActionTriggered()
{
	if (m_filePath.isEmpty()) {
		if (m_notification) {
			m_notification->Push(
				Notify_Type_Warning,
				Pos_Bottom_Right,
				"操作失败",
				"文件路径无效，无法重命名",
				3000
			);
		}
		return;
	}

	QFileInfo fileInfo(m_filePath);
	QString oldFileName = fileInfo.fileName();
	bool ok;

	// 创建 QInputDialog 并清除样式
	QInputDialog dialog(nullptr);  // 父窗口设为 nullptr
	dialog.setWindowTitle("重命名文件");
	dialog.setLabelText(QString("请输入新文件名（含后缀）："));
	dialog.setTextValue(oldFileName);
	dialog.setInputMode(QInputDialog::TextInput);

	// 清除样式表，使用系统默认样式
	dialog.setStyleSheet("");

	// 执行对话框
	ok = dialog.exec() == QDialog::Accepted;
	QString newFileName = dialog.textValue();

	if (!ok || newFileName.isEmpty() || newFileName == oldFileName) {
		return;
	}

	if (newFileName.contains("/") || newFileName.contains("\\") || newFileName.contains(":")) {
		if (m_notification) {
			m_notification->Push(
				Notify_Type_Warning,
				Pos_Bottom_Right,
				"名称无效",
				"文件名不能包含 / \\ : 等特殊字符",
				3000
			);
		}
		return;
	}

	emit renameRequested(m_filePath, newFileName);
}

void RecentItem::onCopyPathActionTriggered()
{
	if (m_filePath.isEmpty()) {
		// 使用 Notification 替代 QMessageBox
		if (m_notification) {
			m_notification->Push(
				Notify_Type_Warning,
				Pos_Bottom_Right,
				"操作失败",
				"文件路径无效，无法复制",
				3000
			);
		}
		return;
	}

	QClipboard* clipboard = QApplication::clipboard();
	clipboard->setText(m_filePath);

	// 成功提示也可以用 Notification
	if (m_notification) {
		m_notification->Push(
			Notify_Type_Success,
			Pos_Bottom_Right,
			"复制成功",
			"路径已复制到剪贴板",
			2000
		);
	}
}

void RecentItem::onCutPathActionTriggered()
{
	if (m_filePath.isEmpty()) {
		// 使用 Notification 替代 QMessageBox
		if (m_notification) {
			m_notification->Push(
				Notify_Type_Warning,
				Pos_Bottom_Right,
				"操作失败",
				"文件路径无效，无法剪切",
				3000
			);
		}
		return;
	}

	QClipboard* clipboard = QApplication::clipboard();
	clipboard->setText(m_filePath);
	setStyleSheet("RecentItem { border-left: 3px solid #F44336; background-color: #FFF2F0; }");

	// 成功提示
	if (m_notification) {
		m_notification->Push(
			Notify_Type_Information,
			Pos_Bottom_Right,
			"剪切成功",
			"路径已剪切（粘贴后原文件将删除）",
			3000
		);
	}
}

void RecentItem::onOpenInExplorerActionTriggered()
{
	if (m_filePath.isEmpty()) {
		// 使用 Notification 替代 QMessageBox
		if (m_notification) {
			m_notification->Push(
				Notify_Type_Warning,
				Pos_Bottom_Right,
				"操作失败",
				"文件路径无效",
				3000
			);
		}
		return;
	}

	QFileInfo fileInfo(m_filePath);
	if (!fileInfo.exists()) {
		// 使用 Notification 替代 QMessageBox
		if (m_notification) {
			m_notification->Push(
				Notify_Type_Error,
				Pos_Bottom_Right,
				"文件不存在",
				"该文件可能已被删除或移动",
				3000
			);
		}
		return;
	}

	QString folderPath = fileInfo.absolutePath();

#ifdef Q_OS_WIN
	QProcess::startDetached("explorer", QStringList() << "/select," << QDir::toNativeSeparators(m_filePath));
#elif defined(Q_OS_MAC)
	QProcess::startDetached("open", QStringList() << "-R" << m_filePath);
#else
	QDesktopServices::openUrl(QUrl::fromLocalFile(folderPath));
#endif
}

void RecentItem::onThemeChanged(ThemeManager::Theme newTheme) {
	if (newTheme == ThemeManager::Theme::Dark) {
		setDarkTheme();
	}
	else {
		setLightTheme();
	}
}

void RecentItem::setName(const QString& name)
{
	m_fullName = name;
	this->setToolTip(name);  // 设置 tooltip
	update();  // 触发重绘
}

void RecentItem::setTimestamp(const QDateTime& timestamp)
{
	QString timeStr;
	QDateTime now = QDateTime::currentDateTime();
	qint64 secondsAgo = timestamp.secsTo(now);

	if (secondsAgo < 60) {
		timeStr = "刚刚";
	}
	else if (secondsAgo < 3600) {
		timeStr = QString("%1分钟前").arg(secondsAgo / 60);
	}
	else if (secondsAgo < 86400) {
		timeStr = QString("%1小时前").arg(secondsAgo / 3600);
	}
	else if (secondsAgo < 86400 * 7) {
		timeStr = QString("%1天前").arg(secondsAgo / 86400);
	}
	else {
		timeStr = timestamp.toString("yyyy-MM-dd hh:mm");
	}

	m_timestampLabel->setText(timeStr);
}

void RecentItem::setTimestamp(const QString& timestampStr)
{
	m_timestampLabel->setText(timestampStr);
}

void RecentItem::mousePressEvent(QMouseEvent* event)
{
	if (event->button() == Qt::LeftButton) {
		qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
		qint64 timeDiff = currentTime - m_lastClickTime;

		if (timeDiff < m_clickThreshold) {
			qDebug() << "过滤快速点击，时间差:" << timeDiff << "ms";
			event->ignore();
			return;
		}

		m_lastClickTime = currentTime;
		emit clicked(m_fullName);
	}
	QWidget::mousePressEvent(event);
}

void RecentItem::contextMenuEvent(QContextMenuEvent* event)
{
	bool isPathValid = !m_filePath.isEmpty();
	m_renameAction->setEnabled(isPathValid);
	m_copyPathAction->setEnabled(isPathValid);
	m_cutPathAction->setEnabled(isPathValid);
	m_openInExplorerAction->setEnabled(isPathValid);

	m_contextMenu->exec(event->globalPos());
}

#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
void RecentItem::enterEvent(QEvent* event)
#else
void RecentItem::enterEvent(QEnterEvent* event)
#endif
{
	m_isHovered = true;
	m_deleteBtn->show();
	update();
	QWidget::enterEvent(event);
}

void RecentItem::leaveEvent(QEvent* event)
{
	m_isHovered = false;
	m_deleteBtn->hide();
	setStyleSheet("");
	update();
	QWidget::leaveEvent(event);
}

void RecentItem::paintEvent(QPaintEvent* event)
{
	QPainter painter(this);
	painter.setRenderHint(QPainter::Antialiasing);

	ThemeManager::Theme currentTheme = ThemeManager::GetInstance().currentTheme();

	// 先绘制悬浮背景
	if (m_isHovered) {
		if (currentTheme == ThemeManager::Theme::Dark) {
			painter.setBrush(QColor(62, 62, 66));
		}
		else {
			painter.setBrush(QColor(232, 244, 253));
		}
		painter.setPen(Qt::NoPen);
		painter.drawRoundedRect(rect(), 6, 6);
	}

	// 再绘制边框
	painter.setBrush(Qt::NoBrush);
	if (currentTheme == ThemeManager::Theme::Dark) {
		painter.setPen(QPen(QColor("#ACC2C8"), 1));
	}
	else {
		painter.setPen(QPen(QColor("#E1E5E9"), 1));
	}
	painter.drawRoundedRect(rect().adjusted(0, 0, -1, -1), 6, 6);

	// 绘制省略的标签名称
	if (!m_fullName.isEmpty()) {
		QRect nameLabelRect = m_nameLabel->geometry();

		// 设置文本颜色
		if (currentTheme == ThemeManager::Theme::Dark) {
			painter.setPen(QColor("#D4D4D4"));
		}
		else {
			painter.setPen(QColor("#2C3E50"));
		}

		// 设置字体
		painter.setFont(m_nameLabel->font());

		// 使用 QFontMetrics 计算省略文本
		QFontMetrics metrics(m_nameLabel->font());
		QString elidedText = metrics.elidedText(
			m_fullName,
			Qt::ElideRight,
			nameLabelRect.width()
		);

		// 绘制省略文本
		painter.drawText(nameLabelRect, Qt::AlignLeft | Qt::AlignVCenter, elidedText);
	}

	// 调用基类 paintEvent，让其他子控件正确绘制
	QWidget::paintEvent(event);
}

// ========== RecentList实现 ==========

RecentList::RecentList(QWidget* parent)
	: QWidget(parent), m_selectedItem(nullptr)
{
	setupUI();
	connect(&ThemeManager::GetInstance(), &ThemeManager::themeChanged, this, &RecentList::onThemeChanged);

	ThemeManager::Theme currentTheme = ThemeManager::GetInstance().currentTheme();
	if (currentTheme == ThemeManager::Theme::Dark) {
		setDarkTheme();
	}
	else {
		setLightTheme();
	}
}

void RecentList::setNotification(Notification* notification)
{
	m_notification = notification;

	// 将通知对象传递给所有已存在的子项
	for (RecentItem* item : m_items) {
		item->setNotification(notification);
	}
}

void RecentList::setupUI()
{
	QVBoxLayout* mainLayout = new QVBoxLayout(this);
	mainLayout->setContentsMargins(0, 0, 0, 0);
	mainLayout->setSpacing(0);

	m_scrollArea = new QScrollArea(this);
	m_scrollArea->setWidgetResizable(true);
	m_scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	m_scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
	m_scrollArea->setFrameShape(QFrame::NoFrame);
	m_scrollArea->setStyleSheet(R"(
        QScrollArea {
            background-color: transparent;
            border: none;
        }
        QScrollBar:vertical {
            background-color: #F8F9FA;
            width: 10px;
            margin: 0px;
            border-radius: 5px;
        }
        QScrollBar::handle:vertical {
            background-color: #CED4DA;
            border-radius: 5px;
            min-height: 20px;
        }
        QScrollBar::handle:vertical:hover {
            background-color: #ADB5BD;
        }
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
            border: none;
            background: none;
        }
    )");

	m_containerWidget = new QWidget();
	m_containerWidget->setStyleSheet("background-color: #FFFFFF;");
	m_containerLayout = new QVBoxLayout(m_containerWidget);
	m_containerLayout->setContentsMargins(2, 6, 2, 6);
	m_containerLayout->setSpacing(5);
	m_containerLayout->addStretch();

	m_containerWidget->setLayout(m_containerLayout);
	m_scrollArea->setWidget(m_containerWidget);

	mainLayout->addWidget(m_scrollArea);
	setLayout(mainLayout);

	setContextMenuPolicy(Qt::DefaultContextMenu);
	m_containerWidget->setContextMenuPolicy(Qt::DefaultContextMenu);

	m_contextMenu = new QMenu(this);
	m_contextMenu->setStyleSheet(R"(
        QMenu {
            background-color: #FFFFFF;
            border: 1px solid #E1E5E9;
            border-radius: 6px;
            padding: 4px;
            color: #495057;
        }
        QMenu::item {
            padding: 6px 16px;
            border-radius: 4px;
            font-size: 13px;
        }
        QMenu::item:selected {
            background-color: #E7F3FF;
            color: #4A90E2;
        }
        QMenu::item:disabled {
            color: #ADB5BD;
        }
        QMenu::separator {
            height: 1px;
            background-color: #E9ECEF;
            margin: 4px 8px;
        }
    )");

	m_newFileAction = new QAction("新建文件", this);
	m_openFolderAction = new QAction("打开文件夹", this);
	m_contextMenu->addAction(m_newFileAction);
	m_contextMenu->addAction(m_openFolderAction);

	connect(m_newFileAction, &QAction::triggered, this, &RecentList::onNewFileActionTriggered);
	connect(m_openFolderAction, &QAction::triggered, this, &RecentList::onOpenFolderActionTriggered);
}

void RecentList::onOpenFolderActionTriggered()
{
	QString folderPath = QFileDialog::getExistingDirectory(
		this,
		"选择文件夹（将加载其中的文件）",
		"",
		QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks
	);

	if (folderPath.isEmpty()) {
		return;
	}

	emit openFolderRequested(folderPath);
}

void RecentList::onThemeChanged(ThemeManager::Theme newTheme) {
	if (newTheme == ThemeManager::Theme::Dark) {
		setDarkTheme();
	}
	else {
		setLightTheme();
	}

	if (m_selectedItem) {
		if (newTheme == ThemeManager::Theme::Dark) {
			m_selectedItem->setStyleSheet("RecentItem { border-left: 3px solid #4A90E2; background-color: #3E3E42; }");
		}
		else {
			m_selectedItem->setStyleSheet("RecentItem { border-left: 3px solid #4A90E2; background-color: #E6F2FF; }");
		}
	}
}

void RecentList::setDarkTheme()
{
	m_containerWidget->setStyleSheet("background-color: #252526;");

	m_scrollArea->setStyleSheet(R"(
        QScrollArea {
            background-color: transparent;
            border: none;
        }
        QScrollBar:vertical {
            background-color: #2D2D30;
            width: 10px;
            margin: 0px;
            border-radius: 5px;
            border: 1px solid #3E3E42;
        }
        QScrollBar::handle:vertical {
            background-color: #5A5A5A;
            border-radius: 5px;
            min-height: 20px;
        }
        QScrollBar::handle:vertical:hover {
            background-color: #6B6B6B;
        }
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
            border: none;
            background: none;
        }
        QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
            background: none;
        }
    )");

	m_contextMenu->setStyleSheet(R"(
        QMenu {
            background-color: #2D2D30;
            border: 1px solid #3E3E42;
            border-radius: 6px;
            padding: 4px;
            color: #E8E8E8;
        }
        QMenu::item {
            padding: 6px 16px;
            border-radius: 4px;
            font-size: 13px;
        }
        QMenu::item:selected {
            background-color: #3E3E42;
            color: #FFFFFF;
        }
        QMenu::item:disabled {
            color: #7A7A7A;
        }
        QMenu::separator {
            height: 1px;
            background-color: #3E3E42;
            margin: 4px 8px;
        }
    )");

	for (RecentItem* item : m_items) {
		item->setDarkTheme();
	}

	update();
}

void RecentList::setLightTheme()
{
	m_containerWidget->setStyleSheet("background-color: #FFFFFF;");

	m_scrollArea->setStyleSheet(R"(
        QScrollArea {
            background-color: transparent;
            border: none;
        }
        QScrollBar:vertical {
            background-color: #F8F9FA;
            width: 10px;
            margin: 0px;
            border-radius: 5px;
        }
        QScrollBar::handle:vertical {
            background-color: #CED4DA;
            border-radius: 5px;
            min-height: 20px;
        }
        QScrollBar::handle:vertical:hover {
            background-color: #ADB5BD;
        }
        QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {
            border: none;
            background: none;
        }
        QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
            background: none;
        }
    )");

	m_contextMenu->setStyleSheet(R"(
        QMenu {
            background-color: #FFFFFF;
            border: 1px solid #E1E5E9;
            border-radius: 6px;
            padding: 4px;
            color: #495057;
        }
        QMenu::item {
            padding: 6px 16px;
            border-radius: 4px;
            font-size: 13px;
        }
        QMenu::item:selected {
            background-color: #E7F3FF;
            color: #4A90E2;
        }
        QMenu::item:disabled {
            color: #ADB5BD;
        }
        QMenu::separator {
            height: 1px;
            background-color: #E9ECEF;
            margin: 4px 8px;
        }
    )");

	for (RecentItem* item : m_items) {
		item->setLightTheme();
	}

	update();
}

void RecentList::smoothScrollToIndex(int index, int duration)
{
	if (index < 0 || index >= m_items.count()) {
		return;
	}

	RecentItem* item = m_items.at(index);
	if (!item) {
		return;
	}

	QScrollBar* vBar = m_scrollArea->verticalScrollBar();
	int itemTop = item->geometry().top();
	int itemHeight = item->height();
	int viewportHeight = m_scrollArea->viewport()->height();
	int targetPos = itemTop - (viewportHeight - itemHeight) / 2;
	targetPos = qBound(vBar->minimum(), targetPos, vBar->maximum());

	QPropertyAnimation* animation = new QPropertyAnimation(vBar, "value");
	animation->setDuration(duration);
	animation->setStartValue(vBar->value());
	animation->setEndValue(targetPos);
	animation->setEasingCurve(QEasingCurve::InOutQuad);
	connect(animation, &QPropertyAnimation::finished, animation, &QPropertyAnimation::deleteLater);
	animation->start();
}

void RecentList::addItem(const QString& name, const QDateTime& timestamp)
{
	RecentItem* item = new RecentItem(name, timestamp, m_containerWidget);
	addItem(item);
}

void RecentList::addItem(const QString& name, const QString& timestampStr)
{
	RecentItem* item = new RecentItem(name, timestampStr, m_containerWidget);
	addItem(item);
}

void RecentList::addItem(RecentItem* item)
{
	if (!item) return;

	// 设置通知对象（如果已设置）
	if (m_notification) {
		item->setNotification(m_notification);
	}

	connect(item, &RecentItem::clicked, this, &RecentList::onItemClicked);
	connect(item, &RecentItem::deleteRequested, this, &RecentList::onItemDeleteRequested);
	connect(item, &RecentItem::renameRequested, this, &RecentList::itemRenameRequested);

	int index = m_containerLayout->count() - 1;
	m_containerLayout->insertWidget(index, item);
	m_items.append(item);
}

void RecentList::insertItem(int index, const QString& name, const QDateTime& timestamp)
{
	RecentItem* item = new RecentItem(name, timestamp, m_containerWidget);
	insertItem(index, item);
}

void RecentList::insertItem(int index, const QString& name, const QString& timestampStr)
{
	RecentItem* item = new RecentItem(name, timestampStr, m_containerWidget);
	insertItem(index, item);
}

void RecentList::insertItem(int index, RecentItem* item)
{
	if (!item || index < 0 || index > m_items.count()) return;

	// 设置通知对象（如果已设置）
	if (m_notification) {
		item->setNotification(m_notification);
	}

	connect(item, &RecentItem::clicked, this, &RecentList::onItemClicked);
	connect(item, &RecentItem::deleteRequested, this, &RecentList::onItemDeleteRequested);

	m_containerLayout->insertWidget(index, item);
	m_items.insert(index, item);
}

void RecentList::removeItem(int index)
{
	if (index < 0 || index >= m_items.count()) return;

	RecentItem* item = m_items.takeAt(index);

	m_containerLayout->removeWidget(item);
	item->deleteLater();
}

void RecentList::removeItem(RecentItem* item)
{
	if (!item) return;

	int index = m_items.indexOf(item);
	if (index >= 0) {
		removeItem(index);
	}
}

void RecentList::removeItemByName(const QString& name)
{
	int index = findItemByName(name);
	if (index >= 0) {
		removeItem(index);
	}
}

void RecentList::clear()
{
	while (!m_items.isEmpty()) {
		RecentItem* item = m_items.takeFirst();
		m_containerLayout->removeWidget(item);
		item->deleteLater();
	}
}

RecentItem* RecentList::itemAt(int index) const
{
	if (index >= 0 && index < m_items.count()) {
		return m_items.at(index);
	}
	return nullptr;
}

int RecentList::findItemByName(const QString& name) const
{
	for (int i = 0; i < m_items.count(); ++i) {
		if (m_items.at(i)->getName() == name) {
			return i;
		}
	}
	return -1;
}

void RecentList::scrollToItem(int index)
{
	smoothScrollToIndex(index);
}

void RecentList::scrollToItem(const QString& name)
{
	int index = findItemByName(name);
	smoothScrollToIndex(index);
}

void RecentList::onItemClicked(const QString& name)
{
	int index = findItemByName(name);
	RecentItem* item = itemAt(index);
	if (!item) {
		qWarning() << "点击了无效Item:" << name;
		return;
	}
	emit itemClicked(name);
}

void RecentList::mousePressEvent(QMouseEvent* event)
{
	QWidget* child = childAt(event->pos());
	if (!child || !qobject_cast<RecentItem*>(child)) {
		if (m_selectedItem) {
			m_selectedItem->setStyleSheet("");
			m_selectedItem = nullptr;
		}
	}
	else {
		RecentItem* clickedItem = qobject_cast<RecentItem*>(child);
		if (clickedItem != m_selectedItem) {
			if (m_selectedItem) {
				m_selectedItem->setStyleSheet("");
			}
			m_selectedItem = clickedItem;

			ThemeManager::Theme currentTheme = ThemeManager::GetInstance().currentTheme();
			if (currentTheme == ThemeManager::Theme::Dark) {
				m_selectedItem->setStyleSheet("RecentItem { border-left: 3px solid #4A90E2; background-color: #3E3E42; }");
			}
			else {
				m_selectedItem->setStyleSheet("RecentItem { border-left: 3px solid #4A90E2; background-color: #E6F2FF; }");
			}
		}
	}
	QWidget::mousePressEvent(event);
}

void RecentList::contextMenuEvent(QContextMenuEvent* event)
{
	QPoint containerPos = m_containerWidget->mapFromGlobal(event->globalPos());

	bool clickedOnItem = false;
	for (RecentItem* item : m_items) {
		if (item->geometry().contains(containerPos)) {
			clickedOnItem = true;
			break;
		}
	}

	if (!clickedOnItem) {
		m_contextMenu->exec(event->globalPos());
	}
}

void RecentList::onItemDeleteRequested(const QString& filePath)
{
	emit itemDeleteRequested(filePath);
}

void RecentList::onNewFileActionTriggered()
{
	emit newFileRequested();
}